{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###   图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#ADT Graph的实现\n",
    "class Vertex:\n",
    "    def __init__(self,key):\n",
    "        self.id = key\n",
    "        self.connectedTo = {}\n",
    "        \n",
    "    def addNeighbor(self,nbr,weight=0):\n",
    "        self.connectedTo[nbr] = weight\n",
    "    \n",
    "    def __str__(self):\n",
    "        return str(self.id) + 'connectecTo:' + str([x.id for x in self.connectedTo])\n",
    "    \n",
    "    def getConnections(self):\n",
    "        return self.connectedTo.keys()\n",
    "    \n",
    "    def getId(self):\n",
    "        return self.id\n",
    "    \n",
    "    def getWeight(self,nbr):\n",
    "        return self.connectedTo[nbr]\n",
    "\n",
    "class Graph:\n",
    "    def __init__(self):\n",
    "        self.verList = {}\n",
    "        self.numVertices = 0\n",
    "    \n",
    "    def addVertex(self,key):\n",
    "        self.numVertices = self.numVertices +1 \n",
    "        newVertex = Vertex(key)\n",
    "        self.verList[key] = newVertex\n",
    "        return newVertex\n",
    "    \n",
    "    def getVertex(self,n):\n",
    "        if n in self.verList:\n",
    "            return self.verList[n]\n",
    "        else:\n",
    "            return None\n",
    "    \n",
    "    def __contains__(self,n):\n",
    "        return n in self.verList\n",
    "    \n",
    "    def addEdge(self,f,t,cost=0):\n",
    "        if f not in self.verList:\n",
    "            nv = self.addVertex(f)\n",
    "        if t not in self.verList:\n",
    "            nv = self.addVertex(t)\n",
    "        self.verList[f].addNeighbor(self.verList[t],cost)\n",
    "    \n",
    "    def getVertices(self):\n",
    "        return self.verList.keys()\n",
    "    \n",
    "    def __iter__(self):\n",
    "        return iter(self,verList.values())\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "faker",
   "language": "python",
   "name": "faker"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
